package com.sendtion.xrichtextdemo.slice;

import com.sendtion.xrichtextdemo.MyApplication;
import com.sendtion.xrichtextdemo.ResourceTable;
import com.sendtion.xrichtextdemo.adapter.MyNoteListAdapter;
import com.sendtion.xrichtextdemo.bean.Note;
import com.sendtion.xrichtextdemo.utils.ItemClickCallBack;
import com.sendtion.xrichtextdemo.utils.MyToast;
import com.sendtion.xrichtextdemo.utils.StringUtils;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.window.service.WindowManager;
import ohos.app.Environment;
import ohos.bundle.IBundleManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * MainAbilitySlice
 *
 * @since 2021-06-22
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbilitySlice");
    private static final int TITLE_COLOR = -13615201;
    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int INT_2 = 2;
    private static final int INT_3 = 3;
    private static final int INT_6 = 6;
    private static final int INT_7 = 7;
    private List<Note> noteList = new ArrayList<>();
    private MyNoteListAdapter myNoteListAdapter;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(TITLE_COLOR);
        initView();
    }

    private void initView() {
        Text mNewnote = (Text) findComponentById(ResourceTable.Id_action_new_note);
        mNewnote.setClickedListener(this::onClick);

        if (verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED
                ||
                verifySelfPermission("ohos.permission.CAMERA") != IBundleManager.PERMISSION_GRANTED
                ||
                verifySelfPermission("ohos.permission.READ_MEDIA") != IBundleManager.PERMISSION_GRANTED) {
            if (canRequestPermission("ohos.permission.READ_MEDIA")) {
                requestPermissionsFromUser(
                        new String[]{"ohos.permission.READ_MEDIA",
                            "ohos.permission.WRITE_MEDIA",
                            "ohos.permission.MEDIA_LOCATION",
                            "ohos.permission.CAMERA",
                            "ohos.permission.WRITE_USER_STORAGE"
                        }, REQUEST_CODE_CHOOSE);
            }
        }
        readFile();
        ListContainer rvlistmain = (ListContainer) findComponentById(ResourceTable.Id_rv_list_main);
        myNoteListAdapter = new MyNoteListAdapter(this, noteList, new ItemClickCallBack() {
            @Override
            public void itemClick(Component component) {
                int indexForComponent = rvlistmain.getIndexForComponent(component);
                removeFile(noteList.get(indexForComponent));
                noteList.remove(indexForComponent);
                myNoteListAdapter.notifyDataSetItemRemoved(indexForComponent);
            }
        });
        rvlistmain.setItemProvider(myNoteListAdapter);
        rvlistmain.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Intent intent = new Intent();
                Operation operationBuilder = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName("com.sendtion.xrichtextdemo.NoteAbility")
                        .build();
                Note note = noteList.get(i);
                note.setGroupName("默认笔记");
                intent.setParam("note", note);
                intent.setOperation(operationBuilder);
                startAbility(intent);
            }
        });
    }

    private void readFile() {
        noteList.clear();
        BufferedReader bufferedReader = null;
        try {
            File file = this.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                StringBuffer sb = new StringBuffer();
                File files1 = files[i];
                String str = null;
                bufferedReader = new BufferedReader(new FileReader(files1));
                while ((str = bufferedReader.readLine()) != null) {
                    sb.append(str);
                }
                String s = sb.toString();
                String name = files1.getName().replaceAll(StringUtils.REPLACERELE, "/");
                String[] split = name.split(":");
                Note fileBean = new Note(s, files1.getName());
                StringBuilder contentBuilder = new StringBuilder();
                StringBuilder timeBuilder = new StringBuilder();
                for (int i1 = 0; i1 < split.length; i1++) {
                    if (i1 < INT_3) {
                        if (i1 != INT_2) {
                            timeBuilder.append(split[i1] + ":");
                        } else {
                            timeBuilder.append(split[i1]);
                        }
                    } else if (i1 == INT_3) {
                        fileBean.setTime(Long.valueOf(split[i1]));
                    } else {
                        contentBuilder.append(split[i1]);
                    }
                }
                fileBean.setCreateTime(timeBuilder.toString());
                fileBean.setTitle(contentBuilder.toString());
                noteList.add(fileBean);
            }
        } catch (FileNotFoundException e) {
            e.getMessage();
        } catch (IOException e) {
            e.getMessage();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
        if (myNoteListAdapter != null) {
            Collections.sort(noteList);
            myNoteListAdapter.notifyDataChanged();
        }
    }

    @Override
    public void onActive() {
        super.onActive();
        readFile();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_action_new_note:
                Intent intent = new Intent();
                intent.setParam("groupName", "默认笔记");
                intent.setParam("flag", 0);
                Operation operationBuilder = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName("com.sendtion.xrichtextdemo.NewAbility")
                        .build();
                intent.setOperation(operationBuilder);
                startAbility(intent);
                break;
            default:
                break;
        }
    }

    private void removeFile(Note note) {
        File file = new File(this.getApplicationContext().getExternalFilesDir(
                Environment.DIRECTORY_DOCUMENTS), note.getFileName());
        boolean isExists = file.exists();
        if (isExists) {
            boolean isDelete = file.delete();
            if (isDelete) {
                MyToast.show(getContext(),"删除成功", MyToast.ToastLayout.BOTTOM);
            }
        }
    }
}